package com.bdth.bdthiss.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bdth.bdthiss.entity.Contract;
import com.bdth.bdthiss.entity.Customer;
import com.bdth.bdthiss.entity.User;
import com.bdth.bdthiss.entity.Userop;
import com.bdth.bdthiss.service.CustomerService;
import com.bdth.bdthiss.service.UserService;
import com.bdth.bdthiss.vo.MessageResult;
import com.bdth.bdthiss.vo.PageVo;
import com.bdth.bdthiss.vo.Pagination;
import com.google.common.io.ByteStreams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * <p>
 * 客户信息 前端控制器
 * </p>
 *
 * @author LGP
 * @since 2019-08-22
 */
@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "index")
    public String index() {
        return "customer/index";
    }

    @RequestMapping(value = "readindex")
    public String readindex() {
        return "customer/readindex";
    }

    @RequestMapping(value = "readform")
    public String readform() {
        return "customer/readform";
    }

    @RequestMapping(value = "xsindex")
    public String xsindex() {
        return "customer/xsindex";
    }

    @RequestMapping(value = "file")
    public String file() {
        return "customer/file";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public PageVo<Customer> getPageList(HttpServletRequest request, Pagination<Customer> pagination,
                                        @RequestParam(required = false) String compname,
                                        @RequestParam(required = false) String headname,
                                        @RequestParam(required = false) String dutynumber,
                                        @RequestParam(required = false) String branch
                                        ){
        Map<String ,Object> query = new HashMap<>();
        //查询条件
        if(compname!=null && !compname.equals(""))
            query.put("compname",compname);
        if(headname!=null && !headname.equals(""))
            query.put("headname",headname);
        if(dutynumber!=null && !dutynumber.equals(""))
            query.put("dutynumber",dutynumber);
        User session = (User)request.getSession().getAttribute("loginUser");
        if(session.getGroupid()!=0){
            String groups = session.getGroups();
            if(groups.equals("销售人员")){
                //只能看到自己的合同
                query.put("signmanid",session.getId());
            }
            if(groups.equals("审核人员") || groups.equals("保密人员")) {
                Integer departid = session.getDepartid();
                EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
                userEntityWrapper.eq("departid",departid);
                List<User> ls = userService.selectList(userEntityWrapper);
                String signmanid="";
                for(User u:ls){
                    signmanid+= u.getId()+",";
                }
                signmanid += "0";
                query.put("signmanid",signmanid);
            }
        }
        //是不是下属单位
        query.put("branch",branch);
        Page<Customer> items = customerService.listPages(pagination, query);
        PageVo<Customer> pageVo = new PageVo<>(items.getRecords(),items.getTotal());
        return pageVo;
    }

    @RequestMapping(value = "form")
    public String form(){
        return "customer/form";
    }

    @RequestMapping(value = "xsform")
    public String xsform(){
        return "customer/xsform";
    }

    @RequestMapping(value = "save")
    @ResponseBody
    public MessageResult save(Customer param){
        EntityWrapper<Customer> entityWrapper = new EntityWrapper<>();
//        entityWrapper.eq("dutynumber",param.getDutynumber());
//        Customer bean = customerService.selectOne(entityWrapper);
//        if(bean!=null){
//            return MessageResult.getError("500","添加客户已存在"+param.getDutynumber());
//        }
        entityWrapper.eq("compname",param.getCompname());
        Customer bean = customerService.selectOne(entityWrapper);
        if(bean!=null){
            return MessageResult.getError("500","添加客户已存在"+param.getCompname());
        }
        param.setUptime(new Date());
        customerService.insert(param);
        return MessageResult.getSuccess("添加数据成功");
    }

    @RequestMapping(value = "update")
    @ResponseBody
    public MessageResult update(Customer param){
        param.setUptime(new Date());
        customerService.updateById(param);
        return MessageResult.getSuccess("修改数据成功");
    }

    @RequestMapping(value = "delete")
    @ResponseBody
    public MessageResult delete(@RequestParam Integer ids){
        customerService.deleteById(ids);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "remove")
    @ResponseBody
    public MessageResult deletes(@RequestParam String ids){
        String[] id = ids.split(",");
       customerService.remove(ids);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "search")
    public String search(){
        return "customer/search";
    }

    @RequestMapping(value = "xssearch")
    public String xssearch(){
        return "customer/xssearch";
    }

    @RequestMapping(value = "fileup")
    @ResponseBody
    public MessageResult save(HttpServletRequest request, Contract param, @RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return MessageResult.getError("500","上传失败，请选择文件");
        }
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
        ServletContext application = request.getServletContext();
        String savePath = "C:\\picture\\";
        // 文件保存目录URL
        String saveUrl = request.getContextPath()+"/files/";
        // 定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        // 检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            return MessageResult.getError("500","上传目录不存在。");
        }
        // 检查目录写权限
        if (!uploadDir.canWrite()) {
            return MessageResult.getError("500","上传目录没有写权限。");
        }

        String dirName = getDirName(extMap,fileExt);
        // 创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        // 检查扩展名

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = new File(savePath, newFileName);
        param.setFiles(saveUrl + newFileName);
        try {
            ByteStreams.copy(file.getInputStream(), new FileOutputStream(uploadedFile));
            //contractService.update(param);
            return MessageResult.getSuccess("导入客户信息成功");
        } catch (Exception e) {
            return MessageResult.getError("500","导入客户信息失败："+e.getMessage());
        }
    }

    private String getDirName(HashMap<String, String> map,String ext){
        for(String key:map.keySet()){
            String value = map.get(key);
            boolean status = value.contains(ext);
            if(status){
                return key;
            }
        }
        return "file";
    }
}

